package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.BuildingListAdapter;
import com.sx.zongzhi.bean.BuildingListBean;
import com.sx.zongzhi.bean.BuildingSearchBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.presenter.BuildingListPest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IBuildingView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * 楼宇管理
 */
public class BuildingActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener
    ,IBuildingView{

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_Total)
    TextView tvTotal;
    @BindView(R.id.imvAdd)
    ImageView imvAdd;
    private BuildingListAdapter listAdapter;
    private List<BuildingListBean.RowsBean> rowsBeanList = new ArrayList<>();
    private BuildingListBean.PermissionBean permissionBean;
    private BuildingListPest listPest;
    private int page = 1, rows = 10;
    private Disposable disposable;
    private String orgId = "";
    private BuildingSearchBean searchBean;
    private boolean isCurrentGrid = false;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_household);
        setTitleName(R.string.building_manage);
        ButterKnife.bind(this);
        setRightImage(R.mipmap.icon_nav_search);
        listPest=new BuildingListPest(this);
        initViews();
        initRx();
    }

    private void initViews() {
        IDataStorage dataStorage= DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        UserBean userBean = dataStorage.load(UserBean.class,getPackageName());
        imvAdd.setVisibility(View.GONE);
        orgId = userBean.getOrg().getId();
        if ("片组片格".equals(userBean.getOrg().getOrgLevel().getDisplayName())){
            isCurrentGrid = true;
        }else {
            isCurrentGrid = false;
            setRightImage2(R.mipmap.icon_nav_position);
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        listAdapter = new BuildingListAdapter(this, R.layout.item_building_list, rowsBeanList);
        listAdapter.setEmptyView(View.inflate(this, R.layout.load_error_view, null));
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                getData();
            }
        }, recyclerView);

        listAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(BuildingActivity.this, BuildingDetailActivity.class)
                        .putExtra("BuildingListBean.RowsBean",rowsBeanList.get(position))
                        .putExtra("userPermission",permissionBean)
                        .putExtra("orgId",orgId));
            }
        });
        onRefresh();
    }

    private void initRx() {
        disposable = MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if (bean.getRequest().equals("BuildingActivity")) {
                            if (bean.getType() == 0) {//选组织结构
                                OrganizingBean oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    orgId = oBean.getId();
                                    if (oBean.isGrid() && permissionBean != null && permissionBean.isAddBuilddatas()){
                                        imvAdd.setVisibility(View.VISIBLE);
                                    }else {
                                        imvAdd.setVisibility(View.GONE);
                                    }
                                }
                                page = 1;
                                getData();
                            } else if (bean.getType() == 2) {//筛选
                                searchBean = (BuildingSearchBean) bean.getMsg();
                                page = 1;
                                getData();
                            } else {//新增修改/删除
                                onRefresh();
                            }
                        }
                    }
                });
    }

    @OnClick({R.id.imv_Right, R.id.imv_Right2, R.id.imvAdd})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.imv_Right://搜索
                startActivity(new Intent(this,BuildingSearchActivity.class));
                break;
            case R.id.imv_Right2://位置
                startActivity(new Intent(this, OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT, "BuildingActivity"));
                break;
            case R.id.imvAdd://添加
                startActivity(new Intent(this, BuildingAddActivity.class).putExtra("orgId",orgId));
                break;
        }
    }

    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(false);
        searchBean=null;
        page = 1;
        getData();
    }

    private void getData() {
        listPest.loadBuildingList(orgId,searchBean,page,rows);
    }



    @Override
    public void showError(String message) {
        if (swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
        ToastUtils.showToast(BuildingActivity.this, message);
    }

    @Override
    protected void onDestroy() {
        if (disposable != null) {
            disposable.dispose();
        }
        super.onDestroy();
    }

    @Override
    public void loadBuildingList(BuildingListBean buildingListBeen) {
        swipeRefreshLayout.setRefreshing(false);
        if (buildingListBeen.getPermission()!=null&&permissionBean==null){
            permissionBean=buildingListBeen.getPermission();
            if (isCurrentGrid&&permissionBean.isAddBuilddatas()){
                imvAdd.setVisibility(View.VISIBLE);
            }else {
                imvAdd.setVisibility(View.GONE);
            }
        }
        if (page == 1) {
            rowsBeanList.clear();
            listAdapter.setNewData(rowsBeanList);
        }
        if (buildingListBeen.getRows() != null && buildingListBeen.getRows().size() > 0) {
            rowsBeanList.addAll(buildingListBeen.getRows());
        }
        if (rowsBeanList.size() == buildingListBeen.getRecords()) {
            listAdapter.loadMoreEnd();
        }else {
            listAdapter.loadMoreComplete();
        }
        listAdapter.notifyDataSetChanged();
        tvTotal.setText("共" + buildingListBeen.getRecords() + "条数据");

    }
}
